<?php


namespace app\app\controller;


class Zhibo extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $typeId = input('type_id', 0, 'intval');
        $typeInfo = n2db('zhibo_type')->where('id', $typeId)->find();
        if (empty($typeInfo)) {
            $this->error('数据有误！');
        }
        $param = input();
        $where = [];
        $limit = intval($param['limit']) < 1 ? 20 : $param['limit'];
        $zhiboTime = strtotime(date('Y-m-d', strtotime('tomorrow')) . ' +1 day');
        $gameName = input('game_name', '', 'trim,urldecode');
        $returnArray = [];

        if (!empty($gameName) && $gameName != '全部') {
            $where['zs.import_name'] = $gameName;
        }
        //得到所有的视频直播
        $list = n2db('zhibo')->alias('z')->join('zhibo_sort zs', 'zs.raw_name = z.zhibo_name  and zs.type_id = z.type_id', 'LEFT')->fieldRaw('z.*,zs.import_name as alias_name,zs.sort as sort')->where('z.type_id', $typeId)
//            ->whereTime('z.zhibo_time', '<', $zhiboTime)
//            ->where('z.zhibo_status', '<>', 3)
            ->where($where)->orderRaw('from_unixtime(z.zhibo_time,"%Y-%m-%d") asc,z.zhibo_time asc,z.zhibo_id asc')->select();
        $returnList = [];
        $weekarray = array("日", "一", "二", "三", "四", "五", "六");
        foreach ($list as $item) {
            $item['zhibo_qiudui'] = explode('$', $item['zhibo_qiudui']);
            $item['zhibo_score'] = explode('$', $item['zhibo_score']);
            $item['zhibo_time_monthday'] = date('m月d日', $item['zhibo_time']);
            $item['zhibo_time_monthday'] .= ' 星期' . $weekarray[date('w', $item['zhibo_time'])];
            $item['zhibo_time_hour'] = date('H:i', $item['zhibo_time']);
            switch ($item['zhibo_status']) {
                case 1:
                    $item['zhibo_status_text'] = '直播中';
                    break;
                case 2:
                    $item['zhibo_status_text'] = '信号中断';
                    break;
                default:
                    $item['zhibo_status_text'] = '尚未开始';
                    break;
            }
            $urls = [];
            $zhiboTextUrls = explode('###', $item["zhibo_play_url"]);
            $zhiboTextUrls = array_filter($zhiboTextUrls);
            foreach ($zhiboTextUrls as $itemTextUrl) {
                list($text, $url) = explode('$', $itemTextUrl);
                if (strpos($url, '//') === 0) {
                    $url = 'https:' . $url;
                }
                $urls[] = [
                    'name' => $text,
                    'url' => $url
                ];
            }

            $item['zhibo_play_url'] = $urls;
            $uniqueScores = array_unique($item['zhibo_score']);
            if (count($uniqueScores) === 1) {
                $item['max_score'] = '';
            } else
                $item['max_score'] = max($item['zhibo_score']);

            if (!isset($returnList[$item['zhibo_time_monthday']])) {
                $returnList[$item['zhibo_time_monthday']] = [];
            }
            $returnList[$item['zhibo_time_monthday']][] = $item;

        }
        foreach ($returnList as $key => $returnItem) {

            $returnArray[] = [
                'monthday' => $key,
                'list' => $returnItem
            ];
        }

        $this->success('获取成功', ['list' => $returnArray, 'page' => 1, 'lastPage' => 1, 'listRows' => $limit]);
    }


    public function indexByPage()
    {
        $typeId = input('type_id', 0, 'intval');
        $typeInfo = n2db('zhibo_type')->where('id', $typeId)->find();
        if (empty($typeInfo)) {
            $this->error('数据有误！');
        }
        $param = input();
        $where = [];
        $limit = intval($param['limit']) < 1 ? 50 : $param['limit'];
        $gameName = input('game_name', '', 'trim,urldecode');
        $returnArray = [];
        $whereTime = [];
        if (!empty($gameName) && $gameName != '全部') {
            $where['zs.import_name'] = $gameName;
        } else {
            $zhiboEndTime = strtotime(date('Y-m-d', strtotime('tomorrow')) . ' +1 day');
            $whereTime['z.zhibo_time'] = ['<', $zhiboEndTime];
        }

        $where = array_merge($where, $whereTime);


        //得到所有的视频直播
        $list = n2db('zhibo')->alias('z')->join('zhibo_sort zs', 'zs.raw_name = z.zhibo_name  and zs.type_id = z.type_id', 'LEFT')->distinct(true)->fieldRaw('z.*,zs.import_name as alias_name,zs.sort as sort')->where('z.type_id', $typeId)
            ->where('z.zhibo_status', '<>', 3)
            ->where($where)->orderRaw('from_unixtime(z.zhibo_time,"%Y-%m-%d") asc,z.zhibo_time asc,z.zhibo_id asc')->paginate($limit);
//        dump(n2db('zhibo')->getLastSql());exit;
        $listArray = $list->items();
        $returnList = [];
        $weekarray = array("日", "一", "二", "三", "四", "五", "六");
        foreach ($listArray as $item) {
            $item['zhibo_qiudui'] = explode('$', $item['zhibo_qiudui']);
            $item['zhibo_score'] = explode('$', $item['zhibo_score']);
            $item['zhibo_time_monthday'] = date('m月d日', $item['zhibo_time']);
            $item['zhibo_time_monthday'] .= ' 星期' . $weekarray[date('w', $item['zhibo_time'])];
            $item['zhibo_time_hour'] = date('H:i', $item['zhibo_time']);
            switch ($item['zhibo_status']) {
                case 1:
                    $item['zhibo_status_text'] = '直播中';
                    break;
                case 2:
                    $item['zhibo_status_text'] = '信号中断';
                    break;
                default:
                    $item['zhibo_status_text'] = '尚未开始';
                    break;
            }
//            $urls = [];
//            $zhiboTextUrls = explode('###', $item["zhibo_play_url"]);
//            $zhiboTextUrls = array_filter($zhiboTextUrls);
//            foreach ($zhiboTextUrls as $itemTextUrl) {
//                list($text, $url) = explode('$', $itemTextUrl);
//                if (strpos($url, '//') === 0) {
//                    $url = 'https:' . $url;
//                }
//                $urls[] = [
//                    'name' => $text,
//                    'url' => $url
//                ];
//            }

//            $item['zhibo_play_url'] = $urls;
            $uniqueScores = array_unique($item['zhibo_score']);
            if (count($uniqueScores) === 1) {
                $item['max_score'] = '';
            } else
                $item['max_score'] = max($item['zhibo_score']);
            $returnList[] = $item;

        }

        $dateArray = cache('zhibo_dates_array_type_id' . $typeId . '_' . md5($gameName));
        if (empty($dateArray)) {
            $dates = n2db('zhibo')->alias('z')->fieldRaw('from_unixtime(zhibo_time,"%Y-%m-%d")')->group('from_unixtime(zhibo_time,"%Y-%m-%d")')->where($whereTime)->column('from_unixtime(zhibo_time,"%Y-%m-%d")');
            $dateArray = [];

            foreach ($dates as $date) {
                $datetime = strtotime($date);
                $dateArray[] = ['name' => date('m月d日', $datetime) . ' 星期' . $weekarray[date('w', $datetime)], "datetime" => $datetime];
//                $dateArray[]=  date('m月d日', $datetime) . ' 星期' . $weekarray[date('w', $datetime)];
            }
            $tomorrow = strtotime('tomorrow');
            cache('zhibo_dates_array_type_id' . $typeId . '_' . md5($gameName), $dateArray, 300);
        }
        $this->success('获取成功', ['list' => array_values($returnList), 'date' => $dateArray, 'page' => $list->currentPage(), 'lastPage' => $list->lastPage(), 'listRows' => $list->listRows()]);
    }

    public function detail()
    {
        $zhibo_id = input('zhibo_id', 0, 'intval');
        $zhiboDetail = n2db('zhibo')->where('zhibo_id', $zhibo_id)->find();
        if (empty($zhiboDetail)) {
            $this->error('获取失败');
        } else {
            $zhiboDetail['zhibo_qiudui'] = explode('$', $zhiboDetail['zhibo_qiudui']);
            $zhiboDetail['zhibo_score'] = explode('$', $zhiboDetail['zhibo_score']);
            $zhiboDetail['zhibo_time_monthday'] = date('m月d日', $zhiboDetail['zhibo_time']);
            $zhiboDetail['zhibo_time_hour'] = date('H:i', $zhiboDetail['zhibo_time']);
            switch ($zhiboDetail['zhibo_status']) {
                case 1:
                    $zhiboDetail['zhibo_status_text'] = '直播中';
                    break;
                case 2:
                    $zhiboDetail['zhibo_status_text'] = '信号中断';
                    break;
                default:
                    $zhiboDetail['zhibo_status_text'] = '尚未开始';
                    break;
            }
            $urls = [];
            $zhiboDetail["zhibo_play_url"] = str_replace('m3u8', 'flv', $zhiboDetail["zhibo_play_url"]);
            $zhiboTextUrls = explode('###', $zhiboDetail["zhibo_play_url"]);
            $zhiboTextUrls = array_filter($zhiboTextUrls);
            foreach ($zhiboTextUrls as $itemTextUrl) {
                list($text, $url) = explode('$', $itemTextUrl);
                if (strpos($url, '//') === 0) {
                    $url = 'https:' . $url;
                }
                $urls[] = [
                    'name' => $text,
                    'url' => $url,
                    'sort' => 1
                ];
            }
            $uniqueScores = array_unique($zhiboDetail['zhibo_score']);
            if (count($uniqueScores) === 1) {
                $item['max_score'] = '';
            } else
                $item['max_score'] = max($zhiboDetail['zhibo_score']);

            $zhiboDetail['zhibo_play_url'] = $urls;

            $shareImages = db('config')->where('name', 'share_image')->whereOr('name', 'player_image')->whereOr('name', 'share_image_' . $zhiboDetail['type_id'])->column('value', 'name');
            if (!empty($shareImages['share_image_' . $zhiboDetail['type_id']])) {
                $shareImages['share_image'] = $shareImages['share_image_' . $zhiboDetail['type_id']];
            }

            $zhiboDetail['share_image'] = $shareImages['share_image'];
            $zhiboDetail['player_image'] = $shareImages['player_image'];

            $this->success('获取成功', $zhiboDetail);
        }
    }

    public function getType()
    {
        $list = n2db('zhibo_type')->where('is_show', 1)->order('sort', 'asc')->select();
        $cachekey = 'Cache_zHibo_type_'.md5(\GuzzleHttp\json_encode($list));
        $cache = cache($cachekey);
        if(empty($cache)) {
            $typeIds = array_column($list, 'id');

            $subList = n2db('zhibo_sort_import')->alias('zsi')->join("zhibo_sort zs", "zs.import_name = zsi.name and zs.type_id = zsi.type_id", 'LEFT')->field('zsi.*,zs.num')->where(function ($query) {
                $query->whereNotNull('zs.import_name')->whereOr('zs.import_name', '<>', '');
            })->whereIn('zsi.type_id', $typeIds)->order('zsi.type_id', 'asc')->order('zsi.sort', 'asc')->select();
//        dump(n2db('zhibo_sort_import')->getLastSql());exit;
            foreach ($subList as $sub) {
                $index = array_search($sub['type_id'], $typeIds);
                $list[$index]['childs'][] = $sub;
            }
            foreach ($list as &$item) {


                if (!empty(trim($item['alias_name']))) {
                    $item['name'] = $item['alias_name'];
                }
                if(isset($item['childs'])) {

                    usort($item['childs'], function ($a, $b) {
                        if ($a['num'] == 0 && $b['num'] > 0) {
                            return 1;
                        }
                        return 0;
                    });
                }else{
                    $item['childs']=[];
                }
                array_unshift($item['childs'], [
                    "sort" => 0,
                    "game_id" => 0,
                    "type_id" => $sub['type_id'],
                    "name" => "全部"
                ]);
            }
            $cache = $list;
            cache($cachekey,$list, 60 * 60);
        }
        $this->success('获取成功', ['list' => $cache]);
    }

    /**
     * 直播访问统计
     */
    public function updateLog()
    {
        $input = input();

        if (empty($input['type_id'])) {
            $input['type_id'] = 0;
        }
        if ($input['type_id'] < 41 || $input['type_id'] > 43) {
            $this->error('类型有误！');
        }
        $time = time();

        try {
            $inputArray = [
                'type_id' => $input['type_id'],
                'zhibo_id' => $input['zhibo_id'],
                'app_id' => $input['app_id'],
                'app_name' => $input['app_name'],
                'zhibo_qiudui' => $input['zhibo_qiudui'],
                'zhibo_name' => $input['zhibo_name'],
                'zhibo_time' => $input['zhibo_time'],
                'system_type' => $input['system_type'],
                'device_id' => $input['device_id'],
                'device_name' => $input['device_name'],
                'time_added' => $time,
            ];
            n2db('zhibo_history')->insertGetId($inputArray);
            $inputArray = [
                'app_id' => $input['app_id'],
                'app_name' => $input['app_name'],
                'key_name' => $input['keyname'],
                'device_id' => $input['device_id'],
                'app_version' => $input['app_version'],
                'zhibo_id' => $input['zhibo_id'],
                'zhibo_name' => '[' . $input['zhibo_name'] . ']' . $input['zhibo_qiudui'],
                'adtype' => '-1',
                'ctime' => $time
            ];
            db('openadlog')->insertGetId($inputArray);
        } catch (\Exception $e) {

        }
        $this->success('记录成功');
    }

    public function syncZhibo()
    {
        $ids = input('ids/a');
        $weekarray = array("日", "一", "二", "三", "四", "五", "六");
        $zhiboLists = n2db('zhibo')->whereIn('zhibo_time', '<', time() + 15)->select();
        foreach ($zhiboLists as &$item) {
            $item['zhibo_qiudui'] = explode('$', $item['zhibo_qiudui']);
            $item['zhibo_score'] = explode('$', $item['zhibo_score']);
            $item['zhibo_time_monthday'] = date('m月d日', $item['zhibo_time']);
            $item['zhibo_time_monthday'] .= ' 星期' . $weekarray[date('w', $item['zhibo_time'])];
            $item['zhibo_time_hour'] = date('H:i', $item['zhibo_time']);
            switch ($item['zhibo_status']) {
                case 1:
                    $item['zhibo_status_text'] = '直播中';
                    break;
                case 2:
                    $item['zhibo_status_text'] = '信号中断';
                    break;
                default:
                    $item['zhibo_status_text'] = '尚未开始';
                    break;
            }
            $uniqueScores = array_unique($item['zhibo_score']);
            if (count($uniqueScores) === 1) {
                $item['max_score'] = '';
            } else
                $item['max_score'] = max($item['zhibo_score']);
        }
        $existIds = array_column($zhiboLists, 'zhibo_id');

        $deleteIds = array_diff($ids, $existIds);

        $this->success('获取成功', [
            'list' => $zhiboLists,
            'deleteIds' => $deleteIds
        ]);
    }

    public function getZhiboNums()
    {
        $type_id = input('type_id', 0, 'intval');
        if ($type_id < 41) {
            $this->error('数据有误！');
        }

        $zhibo_ids = n2db('zhibo')->where('type_id', $type_id)->whereIn('zhibo_status', [1, 2])->column("zhibo_id");
        $this->success('获取成功!', ['zhibo_ids' => $zhibo_ids]);
    }


    public function indexByDate()
    {
        $time = input('time', 0, 'intval');
        if ($time < strtotime('yesterday')) {
            $this->error('时间有误！');
        }
        $endTime = strtotime('+1 day', $time) - 1;
        if ($endTime === false) {
            $this->error('数据有误!');
        }
        $typeId = input('type_id', 0, 'intval');
        $typeInfo = n2db('zhibo_type')->where('id', $typeId)->find();
        if (empty($typeInfo)) {
            $this->error('数据有误！');
        }
        $param = input();
        $where = [];
        $limit = intval($param['limit']) < 1 ? 20 : $param['limit'];
        $gameName = input('game_name', '', 'trim,urldecode');
        $returnArray = [];
        $whereTime = [];
        if (!empty($gameName) && $gameName != '全部') {
            $where['zs.import_name'] = $gameName;
        }
        $whereTime['z.zhibo_time'] = ['between', [$time - 1, $endTime]];

        $where = array_merge($where, $whereTime);

        //得到所有的视频直播
        $list = n2db('zhibo')->alias('z')->join('zhibo_sort zs', 'zs.raw_name = z.zhibo_name and zs.type_id = z.type_id', 'LEFT')->fieldRaw('z.*,zs.import_name as alias_name,zs.sort as sort')->where('z.type_id', $typeId)
            ->where($where)->orderRaw('z.zhibo_time asc,z.zhibo_id asc')->select();
//        dump(n2db('zhibo')->getLastSql());exit;
        $returnList = [];
        $weekarray = array("日", "一", "二", "三", "四", "五", "六");
        $zhibo_time_monthday = date('m月d日', $time) . ' 星期' . $weekarray[date('w', $time)];
        foreach ($list as $item) {
            $item['zhibo_qiudui'] = explode('$', $item['zhibo_qiudui']);
            $item['zhibo_score'] = explode('$', $item['zhibo_score']);
            $item['zhibo_time_monthday'] = $zhibo_time_monthday;
            $item['zhibo_time_hour'] = date('H:i', $item['zhibo_time']);
            switch ($item['zhibo_status']) {
                case 1:
                    $item['zhibo_status_text'] = '直播中';
                    break;
                case 2:
                    $item['zhibo_status_text'] = '信号中断';
                    break;
                default:
                    $item['zhibo_status_text'] = '尚未开始';
                    break;
            }

            $uniqueScores = array_unique($item['zhibo_score']);
            if (count($uniqueScores) === 1) {
                $item['max_score'] = '';
            } else
                $item['max_score'] = max($item['zhibo_score']);

            $returnList[] = $item;

        }

        $this->success('获取成功', ['list' => $returnList, 'zhibo_time_monthday' => $zhibo_time_monthday, 'page' => 1, 'lastPage' => 1, 'listRows' => $limit]);


    }

    public function getTypev1()
    {
        $list = n2db('zhibo_type')->where('is_show', 1)->order('sort', 'asc')->select();
        $cachekey = 'Cache_zHibo_typev1_'.md5(json_encode($list));
//        $cache = cache($cachekey);
        if(empty($cache)) {
            $typeIds = array_column($list, 'id');

            $subList = n2db('zhibo_sort_import')->alias('zsi')->join("zhibo_sort zs", "zs.import_name = zsi.name and zs.type_id = zsi.type_id", 'LEFT')->field('zsi.*,zs.num')->where(function ($query) {
                $query->whereNotNull('zs.import_name')->whereOr('zs.import_name', '<>', '');
            })->whereIn('zsi.type_id', $typeIds)->order('zsi.type_id', 'asc')->order('zsi.sort', 'asc')->select();
//        dump(n2db('zhibo_sort_import')->getLastSql());exit;
            foreach ($subList as $sub) {
                $index = array_search($sub['type_id'], $typeIds);
                $list[$index]['childs'][] = $sub;
            }
            foreach ($list as &$item) {


                if (!empty(trim($item['alias_name']))) {
                    $item['name'] = $item['alias_name'];
                }
                if(isset($item['childs'])) {

                    usort($item['childs'], function ($a, $b) {
                        if ($a['num'] == 0 && $b['num'] > 0) {
                            return 1;
                        }
                        return 0;
                    });
                }else{
                    $item['childs']=[];
                }
                array_unshift($item['childs'], [
                    "sort" => 0,
                    "game_id" => 0,
                    "type_id" => $sub['type_id'],
                    "name" => "全部"
                ]);
            }


            $cache = $list;
            cache($cachekey,$list,12 * 60 * 60);
        }
        $this->success('获取成功', ['list' => $cache]);
    }


}